package com.zigong.app.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.jiongbull.jlog.JLog;
import com.zigong.app.R;
import com.zigong.app.application.Cache;
import com.zigong.app.application.Constances;
import com.zigong.app.base.BaseActivity;
import com.zigong.app.beans.JSBeans;
import com.zigong.app.beans.MallJsonVo;
import com.zigong.app.beans.UserInfoBean;
import com.zigong.app.http.AbsNetCallBack;
import com.zigong.app.http.NetUtils;
import com.zigong.app.ui.utils.GlideCircleTransform;
import com.zigong.app.ui.utils.GlideUtil;
import com.zigong.app.ui.utils.SkipUtil;
import com.zigong.app.ui.utils.TitleUtils;
import com.zigong.app.utils.UserManager;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 积分商城
 */
public class IntegralStoreActivity extends BaseIntegralWebActivity {

    private static final int TO_LOGIN = 2;
    @BindView(R.id.store_avatar)
    protected ImageView ivAvatar;
    @BindView(R.id.store_user_name)
    protected TextView tvUserName;
    @BindView(R.id.store_user_integral)
    protected TextView tvIntegral;
    @BindView(R.id.title_top_edit)
    protected TextView tvRecord;
    private Handler handler;

    public static void startThis(Context context) {
        Intent intent = new Intent(context, IntegralStoreActivity.class);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle(R.string.mine_integral_mall);
        tvRecord.setVisibility(View.VISIBLE);
        tvRecord.setText(R.string.convert_record);
        handler = new Handler( ){
            @Override
            public void handleMessage(Message msg) {
                if (null != msg) {
                    int what = msg.what;
                    switch (what) {
                        case TO_LOGIN:
                            toLoginView();
                            break;
                    }
                }
            }
        };
        if (UserManager.isLoginS()) {
            tvUserName.setText(UserManager.getInstance().getUser().getNickName());
//            GlideUtil.loadAvatorDef(this, UserManager.getInstance().getUser().getAvatar(), ivAvatar);
            GlideUtil.getDynamicGlid(this, UserManager.getInstance().getUser().getAvatar(), true).transform(new GlideCircleTransform(this))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(ivAvatar);
        }
        loadUrl(Constances.MALL_ST_BASE_URL+Constances.URL_MALL);
        SkipUtil.skipToAddUserOperate( this, getOwnerName(),  15, 0, "进入积分商城", "", "" );
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Cache.getInstance().getUserInfo() != null) {
            tvIntegral.setText(Cache.getInstance().getUserInfo().getIntegral() + "");
        } else {
            initUserData();
        }
    }

    @Override
    protected void initInject() {
        initButterknifeBiner(R.layout.activity_integral_store);
    }

    @Override
    protected int getWevViewId() {
        return R.id.store_web;
    }

    @Override
    protected void parseOtherJSMethod(MallJsonVo jsonBean) {
        String method = jsonBean.getMethod().trim();
        if ("detailJson".equalsIgnoreCase(method)) {
            String url = jsonBean.getData().getUrl().trim();
            String json = jsonBean.getData().getJson().trim();
            String thirdPart = jsonBean.getData().getPtype().trim();
            if("1".equalsIgnoreCase(thirdPart)){
                Intent intent = new Intent(this, TYFOH5Activity.class);
                intent.putExtra(TYFOH5Activity.HTML_URL, url);
                startActivity(intent);
            }else {
                CommodityDetailActivity.StartThis(this, url, json);
            }
        }
    }

    @OnClick({R.id.title_top_edit, R.id.store_to_earn_points})
    public void btnClick(View v) {
        switch (v.getId()) {
            case R.id.title_top_edit:
                Intent intent = new Intent(this, RedemptionRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.store_to_earn_points:
                Intent earnIntent = new Intent(this, EarnIntegralActivity.class);
                startActivity(earnIntent);
                break;
        }


    }

    /**
     * 请求用户相关数据，积分等
     */
    private void initUserData() {
        if (UserManager.getInstance().getUser() != null) {
            //TODO 查询用户积分数据
            ArrayMap<String, Object> p = new ArrayMap<>();
            p.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
            p.put("token", UserManager.getInstance().getUser().getToken());
            NetUtils.getNetAdapter().postGetUserData(getOwnerName(), p, new AbsNetCallBack<UserInfoBean>(UserInfoBean.class) {
                @Override
                public void onSuc(UserInfoBean userInfoBean) {
                    Cache.getInstance().setUserInfo(userInfoBean);
                    tvIntegral.setText("" + userInfoBean.getIntegral());
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                }

                @Override
                public boolean whenLoginExpiredBackGround() {
                    Message msg = new Message();
                    msg.what = TO_LOGIN;
                    handler.sendMessage(msg);
                    return true;
                }
            });
        }
    }

    private void toLoginView() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, CODE_REQUEST_LOGIN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_LOGIN && resultCode == RESULT_OK) {
            initUserData();
        }
    }
}
